<?php
declare (strict_types=1);

namespace app\middleware;

use app\traits\JsonResponse;
use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use DomainException;
use InvalidArgumentException;
use UnexpectedValueException;
use Firebase\JWT\Key;

class AuthJwt {
    use JsonResponse;
    public function handle($request, \Closure $next) {
        $jwt = $request->header('Authorization');
        if(empty($jwt)){
            return $this->jsonFail(message:'令牌不能为空');
        }
        $arr = explode(' ',trim($jwt));
        $token = $arr[1];
        try {
             JWT::decode($token, new Key(getSalt(),'HS256'));
        } catch (InvalidArgumentException $e) {
          return $this->jsonFail('token error');
        } catch (DomainException $e) {
            return $this->jsonFail('token error');
        } catch (SignatureInvalidException $e) {
            return $this->jsonFail('token error');
        } catch (BeforeValidException $e) {
            return $this->jsonFail('token error');
        } catch (ExpiredException $e) {
            return $this->jsonFail('token 过期');
        } catch (UnexpectedValueException $e) {
            return $this->jsonFail('token error');
        } catch (\Exception $e){
            return $this->jsonFail('token error');
        }
        return $next($request);
    }
}
